<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--组别数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="groupName"
            placeholder="请输入组别名称模糊查询"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
            @blur="trimOnBlur"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="groupsOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--物料数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="物料编号" prop="itemNum">
            <el-input
              v-model="queryParams.itemNum"
              placeholder="请输入物料编号模糊查询"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
              @blur="trimOnBlur"
            />
          </el-form-item>
          <el-form-item label="物料名称" prop="itemName">
            <el-input
              v-model="queryParams.itemName"
              placeholder="请输入物料名称模糊查询"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
              @blur="trimOnBlur"
            />
          </el-form-item>
          <el-form-item label="物料规格" prop="itemSpecification">
            <el-input
              v-model="queryParams.itemSpecification"
              placeholder="请输入物料规格模糊查询"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
              @blur="trimOnBlur"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:items:add']"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['system:items:edit']"
            >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['system:items:remove']"
            >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              :loading="exportLoading"
              @click="handleExport"
              v-hasPermi="['system:items:export']"
            >导出
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
              v-hasPermi="['system:user:import']"
            >导入</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>
        <el-table v-loading="loading" stripe :data="itemsList" :highlight-current-row="true" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="物料编号" align="center" key="itemNum" prop="itemNum" v-if="columns[0].visible" width="160"/>
          <el-table-column label="物料名称" align="center" key="itemName" prop="itemName" v-if="columns[1].visible"
                           :show-overflow-tooltip="true"/>
          <el-table-column label="规格" align="center" key="itemSpecification" prop="itemSpecification" v-if="columns[2].visible"
                           :show-overflow-tooltip="true"/>
          <el-table-column label="计量单位" align="center" prop="wmsDictMeasuringUnit" width="100" v-if="columns[3].visible">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.wms_dict_measuring_unit" :value="scope.row.wmsDictMeasuringUnit"/>
            </template>
          </el-table-column>
          <el-table-column label="组别" align="center" key="groupName" prop="wmsItemGroups.groupName"
                           v-if="columns[4].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="备注" align="center" key="itemNote" prop="itemNote" v-if="columns[5].visible"
                           :show-overflow-tooltip="true"/>
          <el-table-column
            label="操作"
            align="center"
            width="160"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope" v-if="scope.row.itemUuid !== 1">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:items:edit']"
              >修改
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:items:remove']"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <!--物料列表分页查询-->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    </el-card>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog v-dialogDrag v-dialogDragWidth :title="title" :visible.sync="open" width="400px" append-to-body :close-on-click-modal=false>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="物料编号" prop="itemNum">
              <el-input v-model="form.itemNum" placeholder="请输入物料编号" @blur="trimOnBlur"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="归属组别" prop="groupId">
              <treeselect v-model="form.groupId" :options="groupsOptions" :show-count="true" placeholder="请选择归属组别"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="物料名称" prop="itemName">
              <el-input v-model="form.itemName" placeholder="请输入物料名称" @blur="trimOnBlur"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="规格" prop="itemSpecification">
              <el-input v-model="form.itemSpecification" placeholder="请输入规格"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="计量单位" prop="wmsDictMeasuringUnit">
              <el-select v-model="form.wmsDictMeasuringUnit"
                         placeholder="请选择计量单位" :style="{width: '100%'}">
                <el-option
                  v-for="dict in dict.type.wms_dict_measuring_unit"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.itemNote" type="textarea" autosize placeholder="请输入备注" @blur="trimOnBlur"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog v-dialogDrag v-dialogDragWidth :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
<!--          <div class="el-upload__tip" slot="tip">-->
<!--            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据-->
<!--          </div>-->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {listWmsItems, getWmsItems, delWmsItems, addWmsItems, updateWmsItems, exportWmsItems} from "@/api/wms/wmsItems";
  import{newDocNum} from "@/api/oa/docNum";
  import { getToken } from "@/utils/auth";
  import {treeselect} from "@/api/wms/wmsItemGroups";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import { trimOnBlur } from '@/utils/form'
  export default {
    dicts: ['wms_dict_measuring_unit'],
    name: "Items",
    components: {Treeselect},
    data() {
      return {
        // 遮罩层
        loading: true,
        // 导出遮罩层
        exportLoading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 用户表格数据
        itemsList: null,
        // 弹出层标题
        title: "",
        // 部门树选项
        groupsOptions: undefined,
        // 是否显示弹出层
        open: false,
        // 部门名称
        groupName: undefined,
        // 默认密码
        initPassword: undefined,
        // 日期范围
        dateRange: [],
        // 状态数据字典
        statusOptions: [],
        // 性别状态字典
        sexOptions: [],
        // 表单参数
        form: {},

        defaultProps: {
          children: "children",
          label: "label"
        },

        upload:{
          title: "",
          // 是否显示弹出层
          open: false,
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          headers: { Authorization: "Bearer " + getToken() },
         // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/wms/wms/wmsItems/importData"
        },

        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          itemName: undefined,
          itemNum: undefined,
          itemSpecification: undefined,
          docNum: undefined,
          itemCount: undefined,
          itemNote: undefined,
          groupId: undefined
        },

        // 列信息
        columns: [
          {key: 0, label: `物料编号`, visible: true},
          {key: 1, label: `物料名称`, visible: true},
          {key: 2, label: `规格`, visible: true},
          {key: 3, label: `计量单位`, visible: true},
          {key: 4, label: `组别`, visible: true},
          {key: 5, label: `备注`, visible: true},
        ],

        rules: {
          groupId: [
            {required: true, message: "请选择归属组别", trigger: "change"}
          ],
          itemNum: [
            {required: true, message: "请输入物料编号", trigger: "change"}
          ],
          itemName: [
            {required: true, message: "请输入物料名称", trigger: "change"}
          ],
          wmsDictMeasuringUnit: [
            {required: true, message: "请输入计量单位", trigger: "change"}
          ]
        }
      };
    },

    watch: {
      // 根据名称筛选部门树
      groupName(val) {
        this.$refs.tree.filter(val);
      }
    },

    created() {
      this.getList();
      this.getTreeselect();
    },
    methods: {
      trimOnBlur,

      /** 查询用户列表 */
      getList() {
        this.loading = true;
        listWmsItems(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
            this.itemsList = response.rows;
            this.total = response.total;
            this.loading = false;
          }
        );
      },

      /** 查询部门下拉树结构 */
      getTreeselect() {
        treeselect().then(response => {
          this.groupsOptions = response.data;
        });
      },

      /**筛选节点*/
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },

      /**节点单击事件*/
      handleNodeClick(data) {
        this.queryParams.groupId = data.id;
        this.getList();
      },

      /**取消按钮*/
      cancel() {
        this.open = false;
        this.reset();
      },

      /**表单重置*/
      reset() {
        this.form = {
          itemUuid: undefined,
          groupId: undefined,
          itemName: undefined,
          itemNum: undefined,
          docNum: undefined,
          itemCount: undefined,
          itemNote: undefined,
          wmsDictMeasuringUnit: undefined,
          itemSpecification: undefined,
        };
        this.resetForm("form");
      },

      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },

      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },

      /**多选框选中数据*/
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.itemUuid);
        this.itemNames = selection.map(item => item.itemName);
        this.itemNums = selection.map(item => item.itemNum);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },

      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        newDocNum({preCode:'WMS-', len: 12}).then(response => {
          this.form.itemNum = response.msg
        })
        this.getTreeselect();
        this.open = true;
        this.title = "添加物料";
      },

      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.getTreeselect();
        const itemUuid = row.itemUuid || this.ids;
        getWmsItems(itemUuid).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改物料";
        });
      },

      /** 提交按钮 */
      submitForm: function () {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.itemUuid != undefined) {
              updateWmsItems(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addWmsItems(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },

      /** 删除按钮操作 */
      handleDelete(row) {
        const itemUuids = row.itemUuid || this.ids;
        const itemNums = row.itemNum || this.itemNums;
        const itemNames = row.itemName || this.itemNames;
        this.$modal.confirm('是否确认删除物料编号为"' + itemNums +'",物料名称为"' + itemNames + '"的物料?', '删除确认').then(function(){
          return delWmsItems(itemUuids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {
        });
      },

      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有用户数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportWmsItems(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {
        });
      },

      /** 导入按钮操作 */
      handleImport() {
        this.upload.title = "物料导入";
        this.upload.open = true;
      },

      /** 下载模板操作 */
      importTemplate() {
        this.download('wms/wms/wmsItems/importTemplate', {
          ...this.queryParams
        }, `物料管理_${new Date().toLocaleString()}.xlsx`)
      },

      /**文件上传中处理*/
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },

      /**文件上传成功处理*/
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
        this.getList();
      },

      /**提交上传文件*/
      submitFileForm() {
        this.$refs.upload.submit();
      }
    }
  };
</script>
